﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 软构大作业
{
    public partial class Form3 : Form
    {
        private new AutoAdaptWindowsSize AutoSize;
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }
        public Form3()
        {
            InitializeComponent();
            UpdateValidCode();
            // 设置窗体的KeyPreview属性为true，以便窗体可以接收键盘事件
            this.KeyPreview = true;
            // 为窗体添加KeyDown事件处理
            this.KeyDown += Form3_KeyDown;
        }

        #region 验证码
        private const int ValidCodeLength = 4;//验证码长度        
        private String strValidCode = "";//验证码                        

        //调用自定义函数,更新验证码
        private void UpdateValidCode()
        {
            strValidCode = Class1.CreateRandomCode(ValidCodeLength);//生成随机验证码
            if (strValidCode == "") return;
            Class1.CreateImage(strValidCode, pbox1);//创建验证码图片
        }
        #endregion

        private void Form3_FormClosed(object sender, FormClosedEventArgs e)
        {
            Global.Instance.form3login = null;
            Global.Instance.form1login.Show();
        }
        private void Form3_KeyDown(object sender, KeyEventArgs e)
        {
            // 检查是否按下Enter键
            if (e.KeyCode == Keys.Enter)
            {
                // 触发button1的点击事件
                button1.PerformClick();
                // 标记事件已处理，防止其他控件处理该事件
                e.Handled = true;
                e.SuppressKeyPress = true; // 防止发出"叮"的声音
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            string username = textBox1.Text.Trim();
            string validcode = txtValidCode.Text.Trim();

            // 1. 检查用户名是否为空
            if (string.IsNullOrEmpty(username))
            {
                MessageBox.Show("请输入用户名", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                textBox1.Focus();
                return;
            }

            // 2. 检查验证码是否为空
            if (string.IsNullOrEmpty(validcode))
            {
                MessageBox.Show("请输入验证码", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtValidCode.Focus();
                UpdateValidCode();
                return;
            }

            // 3. 验证验证码是否正确
            if (!ValidateCode(validcode))
            {
                MessageBox.Show("验证码错误", "警告", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                UpdateValidCode();
                txtValidCode.Text = "";
                txtValidCode.Focus();
                return;
            }

            // 4. 检查用户名是否存在
            if (!CheckUsernameExists(username))
            {
                MessageBox.Show("用户名不存在", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                textBox1.Text = "";
                txtValidCode.Text = "";
                textBox1.Focus();
                UpdateValidCode();
                return;
            }


            // 5. 用户名存在且验证码正确，记录用户名并跳转到密码重置界面
            Global.Instance.CurrentUser = new Global.User { Username = username };

            if (Global.Instance.form4login == null)
            {
                Form4 form4 = new Form4();
                Global.Instance.form4login = form4;
            }
            Global.Instance.form4login.Show();
            this.Hide();

            MessageBox.Show("验证通过，请重置密码", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        // 验证验证码是否正确
        private bool ValidateCode(string inputCode)
        {
            return string.Equals(inputCode, strValidCode, StringComparison.OrdinalIgnoreCase);
        }

        // 检查用户名是否存在（使用Data类）
        private bool CheckUsernameExists(string username)
        {
            try
            {
                // 使用Data类执行查询
                string sql = "SELECT COUNT(*) FROM library_db.users WHERE username = @Username";
                DataTable dt = Data.ExecuteQuery(sql, new SqlParameter("@Username", username));

                if (dt != null && dt.Rows.Count > 0)
                {
                    int count = Convert.ToInt32(dt.Rows[0][0]);
                    return count > 0;
                }
                return false;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"数据库查询错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        private void pbox1_Click(object sender, EventArgs e)
        {
            UpdateValidCode();//点击更新验证码
        }

        private void Form3_Load(object sender, EventArgs e)
        {
            UpdateValidCode();//加载更新验证码
        }

        private void button2_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
            txtValidCode.Text = "";
            Global.Instance.form3login.Hide();
            Global.Instance.form1login.Show();
        }

        private void Form3_Load_1(object sender, EventArgs e)
        {
            AutoSize = new AutoAdaptWindowsSize(this);
            this.SizeChanged += new EventHandler(Form_SizeChanged);
        }

        private void Form_SizeChanged(object sender, EventArgs e)
        {//窗体大小改变事件
            if (AutoSize != null) // 一定加这个判断，电脑缩放布局不是100%的时候，会报错
            {
                AutoSize.FormSizeChanged();
            }
        }
    }
}
